<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>纹理合成</title>
  <style>
    body {
      margin: 0;
      overflow: hidden
    }
  </style>
</head>

<body>
  <canvas id="canvas"></canvas>
  <script id="vertexShader" type="x-shader/x-vertex">
    attribute vec4 a_Position;
    attribute vec2 a_Pin;
    varying vec2 v_Pin;
    void main(){
      gl_Position = a_Position;
      v_Pin=a_Pin;
    }
  </script>
  <script id="fragmentShader" type="x-shader/x-fragment">
    precision mediump float;
    uniform sampler2D u_Sampler;
    uniform sampler2D u_Pattern;
    varying vec2 v_Pin;
    void main(){
      vec4 o=texture2D(u_Sampler,v_Pin);
      vec4 p=texture2D(u_Pattern,v_Pin);
      gl_FragColor=p*o;
    }
  </script>
  <script type="module">
    import { imgPromise, initShaders, } from '../jsm/Utils.js';
    import Poly from './jsm/Poly.js';

    const canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    const gl = canvas.getContext('webgl');

    const vsSource = document.getElementById('vertexShader').innerText;
    const fsSource = document.getElementById('fragmentShader').innerText;
    initShaders(gl, vsSource, fsSource);
    gl.clearColor(0.0, 0.0, 0.0, 1.0);

    //数据源
    const source = new Float32Array([
      -0.4, 0.8, 0, 1,
      -0.4, -0.8, 0, 0.0,
      0.4, 0.8, 1.0, 1,
      0.4, -0.8, 1.0, 0.0,
    ]);

    const rect = new Poly({
      gl,
      source,
      type: 'TRIANGLE_STRIP',
      attributes: {
        a_Position: {
          size: 2,
          index: 0
        },
        a_Pin: {
          size: 2,
          index: 2
        },
      }
    })

    const originImg = new Image()
    originImg.src = './images/dress.jpg'

    const pattern = new Image()
    pattern.src = './images/pattern1.jpg'

    Promise.all([
      imgPromise(originImg),
      imgPromise(pattern),
    ]).then(() => {
      rect.maps = {
        u_Sampler: { image: originImg },
        u_Pattern: { image: pattern },
      }
      rect.updateMaps()
      render()
    })

    //渲染
    function render() {
      gl.clear(gl.COLOR_BUFFER_BIT);
      rect.draw()
    }
  </script>
</body>

</html>